package com.hina.rec.common.handler;

import cn.hutool.core.util.CharsetUtil;
import cn.hutool.crypto.SmUtil;
import cn.hutool.crypto.symmetric.SM4;
import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.MappedJdbcTypes;
import org.apache.ibatis.type.MappedTypes;
import org.bouncycastle.pqc.legacy.math.linearalgebra.ByteUtils;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

/**
 * 加密字段TypeHandler
 *
 * @author gengkeke
 * @since 2025/4/1
 */
@MappedJdbcTypes(JdbcType.VARCHAR)
@MappedTypes(String.class)
public class EncryptTypeHandler extends BaseTypeHandler<String> {
    SM4 sm4 = SmUtil.sm4(ByteUtils.fromHexString("50AB3180C2806ED1F47B859DE5013DC4"));

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, String parameter, JdbcType jdbcType) throws SQLException {
        ps.setString(i, sm4.encryptHex(parameter));
    }

    @Override
    public String getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String data = rs.getString(columnName);
        try {
            return sm4.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            return data;
        }
    }

    @Override
    public String getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String data = rs.getString(columnIndex);
        try {
            return sm4.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            return data;
        }
    }

    @Override
    public String getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String data = cs.getString(columnIndex);
        try {
            return sm4.decryptStr(data, CharsetUtil.CHARSET_UTF_8);
        } catch (Exception e) {
            return data;
        }
    }
} 